/**
 * @file 基础布局组件
 * @date 2025/11/20 16:08:01
 * @author lyqjob@yeah.net
 * @description 基础布局组件，包含全局头、侧边栏、内容区域和页脚
 */
import { useState, memo, useRef, useMemo, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Layout, Menu, Button, theme } from 'antd';
import { useSelector } from 'react-redux';
import { 
  MenuFoldOutlined, 
  MenuUnfoldOutlined 
} from '@ant-design/icons';
import GlobalHeader from "@/components/GlobalHeader";
import KeepAliveOutlet from "@/components/KeepAlive";
import TabsContainer from "@/components/TabsContainer";
import AuthGuard from "@/components/AuthGuard";
import SSEManager from "@/components/SSEManager";
import ProgressManager from "@/components/ProgressManager";
import ResponsiveHandler from "@/components/ResponsiveHandler";
import { IconMap } from '@/utils/iconUtils';
import logo from '@/static/images/logo.png';
import styles from './index.less'

const { Header, Content, Footer, Sider } = Layout;


const BasicLayout = memo(() => {
    const containerRef = useRef(null);
    const [collapsed, setCollapsed] = useState(false);
    const { token: { colorBgContainer } } = theme.useToken();
    const location = useLocation();
    const navigate = useNavigate();
    const menulist = useSelector((state) => state.global.menus);

    // 处理侧边栏折叠状态变化
    const handleCollapsedChange = (newCollapsed) => {
        setCollapsed(newCollapsed);
    };

    // 当前选中的菜单项
    const selectedKeys = useMemo(() => {
        return [location.pathname];
    }, [location.pathname]);

    // 记忆化的菜单项处理函数，避免重复计算
    const processMenuItem = useCallback((item) => {
        // 直接使用对象解构创建新对象，避免深拷贝
        const { key, title, name, label, icon, children } = item;
        
        // 处理子菜单（如果有）
        const processedChildren = Array.isArray(children) && children.length > 0 
            ? children.map(processMenuItem).filter(Boolean)
            : undefined;
            
        // 只有在有key的情况下才返回有效菜单项
        if (!key) return null;
            
        return {
            key,
            label: title || name || label,
            icon: icon && IconMap[icon],
            children: processedChildren?.length ? processedChildren : undefined,
        };
    }, []);

    // 处理菜单数据 - 优化版本
    const menuItems = useMemo(() => {
        if (!menulist || menulist.length === 0) return [];

        try {
            // 直接处理原数组，避免使用JSON.parse/stringify进行深拷贝
            // 对于大型菜单，这可以显著提升性能
            return menulist
                .map(processMenuItem)
                .filter(Boolean);
        } catch (error) {
            console.error('菜单数据处理错误:', error);
            return [];
        }
    }, [menulist, processMenuItem]);

    // 菜单点击处理
    const handleMenuClick = useCallback(({ key }) => {
        navigate(key);
    }, [navigate]);


    return (
        <Layout className={styles.layoutbox} ref={containerRef}>
            {/* 认证守卫 - 处理登录状态检查 */}
            <AuthGuard>
                {/* SSE 连接管理 - 处理实时通信 */}
                <SSEManager />

                {/* 进度条管理 - 处理页面切换进度 */}
                <ProgressManager />

                {/* 响应式布局处理 - 处理窗口大小变化 */}
                <ResponsiveHandler
                    collapsed={collapsed}
                    onCollapsedChange={handleCollapsedChange}
                />

                {/* 侧边栏 */}
                <Sider 
                    theme="dark" 
                    trigger={null} 
                    collapsible 
                    collapsed={collapsed}
                >
                    {/* Logo 和用户信息 */}
                    <div className={styles.logobox}>
                        <img src={logo} alt="logo" />
                        <span 
                            style={{
                                opacity: collapsed ? 0 : 1,
                                marginLeft: collapsed ? 0 : '8px',
                                width: collapsed ? 0 : 'auto',
                                overflow: 'hidden',
                                display: 'inline-block'
                            }}
                        >
                            WL 管理系统
                        </span>
                    </div>

                    {/* 导航菜单 */}
                    <Menu
                        theme="dark"
                        mode="inline"
                        defaultSelectedKeys={["/"]}
                        selectedKeys={selectedKeys}
                        onClick={handleMenuClick}
                        style={{
                            height: "90%",
                            overflow: "auto",
                            borderRight: 0,
                        }}
                        items={menuItems}
                    />
                </Sider>

                {/* 主内容区域 */}
                <Layout>
                    {/* 头部 */}
                    <Header
                        className={styles.headerbox}
                        style={{
                            background: colorBgContainer,
                        }}
                    >
                        <Button
                            type="text"
                            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                            // 使用函数式更新避免依赖collapsed状态
                            onClick={useCallback(() => {
                                setCollapsed(prev => !prev);
                            }, [])}
                                style={{
                                    fontSize: "16px",
                                    width: 56,
                                    height: 56,
                                }}
                            />
                        <GlobalHeader />
                    </Header>

                    {/* 内容区域 */}
                    <Content className={styles.contentbox}>
                        <TabsContainer />
                        <div className={styles.pageContent}>
                            <KeepAliveOutlet />
                        </div>
                    </Content>

                    {/* 底部 */}
                    <Footer style={{ textAlign: 'center', paddingTop: 0, height: 40 ,width:'100%',lineHeight:'40px',padding:'0 10px',whiteSpace:'no-wrap',overflow: 'hidden',textOverflow: 'ellipsis'}}>
                        React + Node.js + MySQL + Ant Design © 2025  豫ICP备19036863号
                    </Footer>
                </Layout>
            </AuthGuard>
        </Layout>
    );
});

export default BasicLayout;
